<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
.mark{
    position:absolute;
    height:100px;
    width:100px;
    left:100px;
    top:180px;
    border:1px solid #000;
    cursor:move;
}
    </style>
</head>
<body>
    <input type="file" onchange='change(this)'/>
<canvas id="c1"></canvas> //显示原图像
<div class="mark" id="mark"></div>
<canvas id="c3"></canvas> //显示剪切后的图像
<script>
    function change(node){
    // var windowURL = window.URL || window.webkitURL;
    // var dataURL = windowURL.createObjectURL(e.target.value);
    var imgURL = "";  
    console.log(node.files)
    try{  
        var file = null;  
        if(node.files && node.files[0] ){  
            file = node.files[0];  
        }else if(node.files && node.files.item(0)) {  
            file = node.files.item(0);  
        }  
        console.log(file)
        //Firefox 因安全性问题已无法直接通过input[file].value 获取完整的文件路径  
        try{  
            imgURL =  file.getAsDataURL();  
        }catch(e){  
            console.log(e)
            console.log(window.URL)
            imgURL = window.URL.createObjectURL(file);  
        }  
    }catch(e){  
        console.log(e)
        if (node.files && node.files[0]) {  
            var reader = new FileReader();  
            reader.onload = function (e) {  
                imgURL = e.target.result;  
            };  
            reader.readAsDataURL(node.files[0]);  
        }  
    } 
   clip(imgURL)
  
}
    function clip(url){
        var canvas1 = document.getElementById("c1")
    var oMark = document.getElementById("mark")
    var canvas3= document.getElementById("c3")
     canvas1.height = 300;
    canvas1.width=300;
    canvas3.height=100;
    canvas3.width=100;
    var cxt1 = canvas1.getContext("2d")
    var img = new Image();
    img.src =url;
    var srcX = oMark.offsetLeft-canvas1.getBoundingClientRect().top;
    var srcY = oMark.offsetTop-canvas1.getBoundingClientRect().top;
    var sWidth = oMark.offsetWidth;
    var sHeight = oMark.offsetHeight;

    var canvas2 = document.createElement("canvas")
    var cxt2=canvas2.getContext("2d")
    img.onload = function(){
        cxt1.drawImage(img,0,0,canvas1.width,canvas1.height);
        console.log(srcX)
        console.log(srcY)
        console.log(sWidth)
        console.log(sHeight)
        var dataImg = cxt1.getImageData(srcX,srcY,sWidth,sHeight)
        canvas2.width = sWidth;
        canvas2.height = sHeight;
        cxt2.putImageData(dataImg,0,0,0,0,canvas2.width,canvas2.height)
        var img2 = canvas2.toDataURL("image/png");
        var cxt3=canvas3.getContext("2d")
        var img3 = new Image();
        img3.src = img2;
        img3.onload  = function(){
            cxt3.drawImage(img3,0,0,canvas3.width,canvas3.height)
        }

    }
    }
   
</script>
</body>
</html>